package com.lsh.payment.service.common;

import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.lsh.payment.api.model.basevo.CommonResult;
import com.lsh.payment.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 16/7/15
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Slf4j
public class BusinessExceptionMapper implements ExceptionMapper<BusinessException> {

    /**
     * Map an exception to a {@link Response}. Returning
     * {@code null} results in a {@link Response.Status#NO_CONTENT}
     * response. Throwing a runtime exception results in a
     * {@link Response.Status#INTERNAL_SERVER_ERROR} response.
     *
     * @param exception the exception to map to a response.
     * @return a response mapped from the supplied exception.
     */
    @Override
    public Response toResponse(BusinessException exception) {

        CommonResult<Integer> commonResult;
        try {
            if (exception == null) {
                commonResult = new CommonResult<>("10010001", "参数错误或处理异常");
            } else {
                commonResult = new CommonResult<>(exception.getCode(), exception.getMessage());
            }
            log.error(" [业务异常] {}", JSON.toJSONString(exception));
        } catch (Exception e) {
            commonResult = new CommonResult<>("10010001", "参数错误或处理异常");
        }

        return Response.ok().entity(commonResult)
                .type(ContentType.APPLICATION_JSON_UTF_8)
                .header("X-Frame-Options", "SAMEORIGIN")
                .build();
    }

}
